﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;

using Telerik.Windows.Controls;
using BrokerBase.Lib.Product;
using NHibernate;
using Broker.View.ProductView;
using Broker.View.PolicyView;
using Broker.View.CompanyView;
using BrokerBase.Lib.Person;
using BrokerBase.Lib.Policy;
using Broker.View.PersonView;

using Broker.Mgr.SaleView;
using BrokerBase.Lib.Company;
using Broker.View.ViewModel;
using System.IO;
using System.ComponentModel;

namespace Broker.Mgr
{
    /// <summary>
    /// Interaction logic for MainForm.xaml
    /// </summary>
    public partial class MainForm
    {
        private BackgroundWorker buildCatlogWorker = new BackgroundWorker();

        public MainForm()
        {
            InitializeComponent();

            Loaded += new RoutedEventHandler(MainForm_Loaded);

            
        }

        void MainForm_Loaded(object sender, RoutedEventArgs e)
        {
            AppGlobal.MinWin = this;
            Broker.View.LibGlobal.MainWin = this;

            buildCatlogWorker.DoWork += BuildCatalog;
            buildCatlogWorker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(buildCatlogWorker_RunWorkerCompleted);
        }

        void buildCatlogWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            MessageBox.Show("产品目录创建完毕!");
            buyRoot.IsBusy = false;
        }

        private void AddOrDisplayTab(Page page,string title)
        {
            RadDocumentPane rdp = GetPane(title);

            if (rdp != null)
            {
                pgPlatform.SelectedItem = rdp;
            }
            else
            {
                Frame frame = new Frame();
                
                frame.Content = page;

                RadDocumentPane pane = new RadDocumentPane();

                pane.Header = title;
                pane.Tag = title;
                pane.Content = frame;

                pgPlatform.Items.Add(pane);
            }

        }

        private RadDocumentPane GetPane(string tag)
        {
            RadDocumentPane rdp = null;

            foreach (object o in pgPlatform.Items)
            {
                RadDocumentPane dp = o as RadDocumentPane;

                if (dp.Tag!=null && dp.Tag.ToString() == tag)
                {
                    rdp = dp;
                    break;
                }
            }

            return rdp;
        }

        private void RadTreeViewItem_PreviewMouseDown(object sender, MouseButtonEventArgs e)
        {
            try
            {
                string name = (sender as RadTreeViewItem).Name;

                if (name == "tviCompanyList")
                {
                    CompanyListPage page = new CompanyListPage();

                    AddOrDisplayTab(page, "公司列表");
                }
                else if (name == "tviProductList")
                {
                    ProductListPage page = new ProductListPage();

                    AddOrDisplayTab(page, "产品列表");
                }
                else if (name == "tviFast")
                {
                    IPerson holder = new Person();
                    holder.Birthday = new DateTime(1962, 6, 1);
                    holder.Sex = SexType.Male;

                    IPerson insurant = new Person();
                    insurant.Birthday = new DateTime(1982, 6, 1);
                    insurant.Sex = SexType.Male;

                    IScheme scheme = new Scheme();
                    scheme.Insurant = insurant;
                    scheme.Holder = holder;
                    scheme.BizDate = DateTime.Now;
                    scheme.CreateDate = DateTime.Now;

                    Scheme2Form frm = new Scheme2Form(scheme, SchemeType.Fast);

                    frm.WindowStartupLocation = WindowStartupLocation.CenterOwner;
                    frm.Owner = AppGlobal.MinWin;
                    frm.Show();

                }
                else if (name == "tviActiveCodeList")
                {
                    ActiveCodeListPage page = new ActiveCodeListPage();
                    AddOrDisplayTab(page, "激活码");
                }
                else if (name == "tviScoreRuleList")
                {
                    ScorePolicyListPage page = new ScorePolicyListPage();
                    AddOrDisplayTab(page, "积分政策");
                }
                else if (name == "tviClientList")
                {
                    ClientListPage page = new ClientListPage();

                    AddOrDisplayTab(page, "注册用户");
                }
                else if (name == "tviConfig")
                {
                    ConfigPage page = new ConfigPage();

                    AddOrDisplayTab(page, "设置");
                }
                else if (name == "tviBuildCatalog")
                {
                    if (MessageBox.Show("是否要创建产品目录?", "提示", MessageBoxButton.YesNo) == MessageBoxResult.Yes)
                    {
                        if (buildCatlogWorker.IsBusy)
                        {
                            MessageBox.Show("正在创建目录...");
                        }
                        else
                        {
                            buyRoot.IsBusy = true;
                            buildCatlogWorker.RunWorkerAsync();
                        }
                    }

                    
                }


            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void BuildCatalog(object sender, DoWorkEventArgs e)
        {

            ISession sess = null;

            try
            {
                sess = AppGlobal.HbmSessionFactory.OpenSession();

                IEnumerable<ICompany> companies = sess.CreateQuery("from Company").Enumerable<ICompany>();

                string path = Environment.CurrentDirectory + @"\产品介绍";

                if (!System.IO.Directory.Exists(path))
                {
                    Directory.CreateDirectory(path);
                }

                string dirnote = path + @"\dir.txt";

                if (File.Exists(dirnote))
                {
                    File.Delete(dirnote);
                }

                StreamWriter sw = new StreamWriter(dirnote);


                foreach (ICompany cmp in companies)
                {
                    string companyPath = path + @"\" + cmp.Name;

                    if (!Directory.Exists(companyPath))
                    {
                        Directory.CreateDirectory(companyPath);
                    }

                    IEnumerable<IProduct> products = sess.CreateQuery("from Product where CompanyId="+cmp.Id).Enumerable<IProduct>();

                    foreach (IProduct p in products)
                    {
                        string productPath = companyPath + @"\" + p.Name;
                        if (!Directory.Exists(productPath))
                        {
                            Directory.CreateDirectory(productPath);

                            sw.WriteLine(productPath);
                        }
                        else
                        {
                            DirectoryInfo di = new DirectoryInfo(productPath);

                            if (di.GetFiles().Length == 0 && di.GetDirectories().Length == 0)
                            {
                                sw.WriteLine(productPath);
                            }
                        }

                        this.Dispatcher.Invoke(new Action(() =>
                         {
                             buyRoot.BusyContent = p.Name;
                         }));
                    }

                }

                sw.Close();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            finally
            {
                if (sess != null)
                {
                    sess.Close();
                }
            }
        }
    }
}
